package com.demo.javase.day76;

import java.io.*;

/**
 * @Author bug菌
 * @Date 2023-12-27 17:11
 */
public class SerializationExampleTest {

    public static void main(String[] args) {
        // 创建一个对象并设置值
        Person person = new Person("John", 30);

        // 将对象序列化到文件
        try {
            FileOutputStream fileOut = new FileOutputStream("./person.txt");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
            System.out.println("对象已序列化到person.txt文件");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将文件中的对象反序列化
        try {
            FileInputStream fileIn = new FileInputStream("./person.txt");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Person serializedPerson = (Person) in.readObject();
            in.close();
            fileIn.close();

            System.out.println("反序列化得到的对象：");
            System.out.println("姓名：" + serializedPerson.getName());
            System.out.println("年龄：" + serializedPerson.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
